package com.weixin.service;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TokenUtil {

    private static ConcurrentHashMap<String, List<String>> tokenMaps = new ConcurrentHashMap<String, List<String>>();

    public synchronized String generateToken(String key){
        String uuid = UUID.randomUUID().toString();
        if(tokenMaps.contains(key)){
            tokenMaps.get(key).add(uuid);
        }else{
            List<String> uuids = new ArrayList<>();
            uuids.add(uuid);
            tokenMaps.put(key,uuids);
        }
        return uuid;
    }

    public synchronized boolean checkToken(String key,String uuid){
        if(tokenMaps.containsKey(key)){
            List<String> strings = tokenMaps.get(key);
            if(strings.contains(uuid)){
                strings.remove(uuid);
                return true;
            }
        }
        return false;
    }

}
